"ui";
ui.layout(
    <vertical>
        <text marginTop="50" text="运行脚本前请先授予权限" textColor="red"/>
        <text text="脚本会自动更新,但如果无法运行请手动点击更新脚本"/>
        <horizontal>
            <button id="win" text="1.授予悬浮窗权限"/>
            <button id="auto" text="2.授予无障碍权限"/>
            <button id="update" text="更新脚本"/>
        </horizontal>

        <text marginTop="50" text="淘宝任务" textColor="red"/>
        <text text="幻想岛任务需要先完成新手教程"/>
        <horizontal>
            <button id="startjs" text="幻想岛"/>
            <button id="tb_huichang" text="红包会场任务"/>
            <button id="tb_luck" text="预售会场幸运值"/>
        </horizontal>

        <text marginTop="50" text="京东任务" textColor="red"/>
        <horizontal>
            <button id="jd_hb" text="打卡任务"/>
        </horizontal>

    </vertical>
);

//指定确定按钮点击时要执行的动作
ui.win.click(function(){
    if (!floaty.checkPermission()) {
        // 没有悬浮窗权限，提示用户并跳转请求
        toast("本脚本需要悬浮窗权限来显示悬浮窗，请在随后的界面中允许并重新运行本脚本。");
        floaty.requestPermission();
        exit();
    } else {
        toastLog('已有悬浮窗权限');
    }
});

ui.auto.click(function(){
    try {
        auto();
        toastLog('已有无障碍权限');
    } catch (e) {
        toastLog('授予无障碍权限失败');
        console.error("授予无障碍权限失败");
        console.trace(e);
    }
});

const giteeUrl = "https://gitee.com/k_fuling/test/raw/master/src/"
const baseUrl = "https://fuling996.github.io/test/"

function getSetting(jsName) {
    threads.start(function(){
        const result = http.get(baseUrl + jsName).body.string();
        files.write("/sdcard/脚本/" + jsName, result);
    });
}

function update() {
    //判断是否需要更新
    var version;
    var newVersion;
    try {
        version = files.read("/sdcard/脚本/version.txt");
    } catch (e) {
        threads.start(function(){
            const result = http.get(giteeUrl + "version.txt").body.string();
            files.write("/sdcard/脚本/version.txt", result);
        });

        version = "";
    }

    var t = threads.start(function(){
        newVersion = http.get(giteeUrl + "version.txt").body.string()
    });
    t.join();

    if (version !== newVersion) {
        //需要更新
        toastLog('正在更新脚本');
        getSetting("start.js")
        getSetting("tb_huichang.js")
        getSetting("tb_luck.js")
        getSetting("jd_hb.js")
        toastLog('更新完毕');
    }
}

ui.startjs.click(function(){
    engines.execScriptFile("/sdcard/脚本/" + "start.js");
});

ui.tb_huichang.click(function(){
    engines.execScriptFile("/sdcard/脚本/" + "tb_huichang.js");
});

ui.tb_luck.click(function(){
    engines.execScriptFile("/sdcard/脚本/" + "tb_luck.js");
});

ui.jd_hb.click(function(){
    engines.execScriptFile("/sdcard/脚本/" + "jd_hb.js");
});

ui.update.click(function(){
    files.remove("/sdcard/脚本/version.txt")
    update();
});

update();
